package com.zdpx.pxframework.datapermission.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.zdpx.pxframework.datapermission.rule.DataPermissionRule;
import org.apache.ibatis.mapping.MappedStatement;

import java.util.List;

/**
 * Sql解析上下文
 *
 * @Description:
 * @Author: Cheng XiaoXiao
 * @Date: 2022/6/4 14:52
 */
public class SqlParseContextHolder {
    /**
     * 该 {@link MappedStatement} 对应的规则
     */
    private static final ThreadLocal<List<DataPermissionRule>> RULES = new TransmittableThreadLocal<>();
    /**
     * SQL 是否进行重写
     */
    private static final ThreadLocal<Boolean> REWRITE = new TransmittableThreadLocal<>();

    /**
     * 初始化
     *
     * @param rules 数据权限规则
     */
    public static void init(List<DataPermissionRule> rules) {
        RULES.set(rules);
        REWRITE.set(false);
    }

    /**
     * 清空
     */
    public static void clear() {
        RULES.remove();
        REWRITE.remove();
    }

    /**
     * 获取是否重写
     *
     * @return 是否重写
     */
    public static boolean getRewrite() {
        return REWRITE.get();
    }

    /**
     * 设置重写状态
     *
     * @param rewrite 状态
     */
    public static void setRewrite(boolean rewrite) {
        REWRITE.set(rewrite);
    }

    /**
     * 获取数据权限规则
     *
     * @return 数据权限规则liebiao
     */
    public static List<DataPermissionRule> getRules() {
        return RULES.get();
    }
}
